package com.hnd.springframework.beans.factory.support;

import com.hnd.springframework.beans.BeanException;
import com.hnd.springframework.beans.factory.BeanFactory;
import com.hnd.springframework.beans.factory.config.BeanDefinition;

/**
 * 模板 、
 * 创建bean的步骤
 * 1.获取beanDefine
 * 2.实例化bean
 * 3.获取bean
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory {

    @Override
    public Object getBean(String beanName) {
        return doGetBean(beanName, null);
    }

    @Override
    public Object getBean(String beanName, Object... args) throws BeanException {
        return null;
    }


    public <T> T doGetBean(String beanName, Object... args) {
        Object bean = getSingleton(beanName);
        if (bean != null) {
            return (T) bean;
        }
        //获取bena定义
        BeanDefinition beanDefinition = getBeanDefinition(beanName);
        //创建bean
        return (T) createBean(beanName, beanDefinition, args);
    }

    @Override
    public <T> T getBean(String beanName, Class<T> requestTypes) {
        return (T) getBean(beanName, requestTypes);
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeanException;

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object... args) throws BeanException;
}
